package vn.gq.tym.view;

import vn.gq.tym.model.CategoryAdapter;
import vn.gq.tym.model.bean.CategoryItem;
import vn.gq.tym.truyennguoilonfull.R;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.widget.BaseFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;

public class CategoryFragment extends BaseFragment implements OnItemClickListener {

	public static final String PREV_SCR_TAG = "prev_scr_tag";
	
	private ListView mListView;
	private ProgressBar mProgressBar;
	private CategoryAdapter mAdapter;
	private String mDataPath;
	
	public static CategoryFragment newInstance(String dataPath) {
		CategoryFragment f = new CategoryFragment();
		Bundle args = new Bundle();
		args.putString("PATH", dataPath);
		f.setArguments(args);
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			mDataPath = getArguments().getString("PATH");
			if ("".equals(mDataPath)) mDataPath = "";
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.fragment_chapter;
	}

	@Override
	public int getContainerId() {
		return R.id.layout_container;
	}
	
	@Override
	public void createView(Bundle savedInstanceState) {
		mListView = (ListView) findViewById(R.id.list);
		mListView.setOnItemClickListener(this);
		mListView.setVisibility(View.GONE);
		mProgressBar = (ProgressBar) findViewById(R.id.loading);
		mProgressBar.setVisibility(View.VISIBLE);
		mAdapter = new CategoryAdapter(getActivity());
		mAdapter.load(mDataPath, new Runnable() {
			
			@Override
			public void run() {
				mListView.setAdapter(mAdapter);
				mListView.setVisibility(View.VISIBLE);
				mProgressBar.setVisibility(View.GONE);
				if (getActivity() instanceof IClientListener) {
					((IClientListener) getActivity()).onDone(0, null);
				}
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (id > -1) {
			CategoryItem catItem = (CategoryItem) mAdapter.getItem(position);
			ChapterFragment chapterFragment = ChapterFragment.newInstance(catItem);
			startFragment(chapterFragment.getContainerId(), chapterFragment, chapterFragment.getFragmentTag());
		}
	}
}
